<?php
class Task extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->model('tourism_order_model', 'tourism_order');
        $this->load->model('tourism_order_product_model', 'tourism_order_product');
        $this->load->model('tourism_order_product_profit_model', 'tourism_order_product_profit');
        $this->load->model('tourism_order_reviews_model', 'tourism_order_reviews');
        $this->load->model('tourism_goods_attr_model', 'tourism_goods_attr');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('cash_record_model', 'cash_record');
    }

    /**
     * 自动关闭订单
     * $order_state  = 1
     * $order_status = 1
     */
    public function undoTourismOrder()
    {
        //24小时 未付款的订单
        $result = $this->tourism_order->findByParamsOrder(array('created_at'=>date('Y-m-d H:i:s', strtotime('-1 day')), 'order_status'=>2));
        if ($result->num_rows() <= 0) {
            return ;
        }
        $order = $result->result();
        foreach ($order as $item) {
            $order_ids[] = $item->order_id;
        }
        if (empty($order_ids)) {
            return ;
        }
        //事物处理中
        $this->db->trans_begin();
        $stockInfo = $this->tourism_order_product->findByParamProduct(array('order_ids'=>$order_ids));
        foreach ($stockInfo->result() as $key => $item) {
            $this->tourism_goods_attr->returnStock(array('goods_attr_id'=>$item->goods_attr_id, 'refund_num'=>$item->refund_num));
        }
        $isUndoOrder = $this->tourism_order->UndoNotPayOrder($order_ids);
        if ($this->db->trans_status() === FALSE || !$isUndoOrder) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
        echo implode(',', $order_ids);exit;
    }

    /**
     * 发货7天后未确认收货的，自动确认收货
     * $order_state  = 3
     * $order_status = 5
     */
    public function receiveTourismOrder()
    {
        $send_time = date('Y-m-d H:i:s', strtotime('-1 week'));
        $result = $this->tourism_order->findByParamsOrder(array('send_time'=>$send_time, 'order_status'=>4));
        if ($result->num_rows() <= 0) {
            return ;
        }
        $order = $result->result();
        foreach ($order as $item) {
            $order_ids[] = $item->order_id;
        }
        if (empty($order_ids)) {
            return ;
        }
        $this->db->trans_begin();
        $isReceive = $this->tourism_order->receiveTourismOrder($order_ids);
        if ($this->db->trans_status() === FALSE || !$isReceive) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
        echo implode(',', $order_ids);exit;
    }
    
    /**
     * 确认收货后7天未评价，则系统自动好评，然后分钱
     * $order_state  = 4
     * $order_status = 6
     */
    public function reviewsTourismOrder()
    {
        /**
         * order_status = 5
         * receive_time > date('Y-m-d H:i:s', strtotime('-1 week'))
         */
        $result = $this->tourism_order->findByParamsOrder(array('order_status'=>5, 'receive_time'=>date('Y-m-d H:i:s', strtotime('-1 week'))));
        if ($result->num_rows() <= 0) {
            return ;
        }
        $orders = $result->result();
        $ordersInfo = array();
        foreach ($orders as $item) {
            $order_ids[] = $item->order_id;
            $ordersInfo[$item->order_id]['payer_uid']  = $item->payer_uid;
            $ordersInfo[$item->order_id]['user_name']  = $item->user_name;
            $ordersInfo[$item->order_id]['seller_uid'] = $item->seller_uid;
        }
        if (empty($order_ids) || empty($ordersInfo)) {
            return ;
        }
        //获取订单下所有产品
        $result1 = $this->tourism_order_product->findByParamProduct(array('order_ids'=>$order_ids));
        if ($result1->num_rows() <= 0) {
            return ;
        }
        $orderPoduct = $result1->result();
        $orderReviews = array();
        foreach ($orderPoduct as $key=>$product) {
            $order_product_ids[] = $product->order_product_id;
            $orderReviews[$key]['order_product_id']= $product->order_product_id;
            $orderReviews[$key]['order_id']        = $product->order_id;
            $orderReviews[$key]['goods_attr_id']   = $product->goods_attr_id;
            $orderReviews[$key]['goods_image']     = $product->goods_image;
            $orderReviews[$key]['attribute_value'] = $product->attribute_value;
            $orderReviews[$key]['goods_name']      = $product->goods_name;
            $orderReviews[$key]['uid']             = $ordersInfo[$product->order_id]['payer_uid'];
            $orderReviews[$key]['user_name']       = $ordersInfo[$product->order_id]['user_name'];
            $orderReviews[$key]['user_content']    = '好评！';
            $orderReviews[$key]['status']          = 2; //审核通过
            $orderReviews[$key]['review_score']    = 5; //好评分
        }
        if (empty($order_product_ids) || empty($orderReviews)) {
            return ;
        }
        //获取订单产品下所有分润信息
        $result2 = $this->tourism_order_product_profit->findByParamProductProfit(array('order_product_ids'=>$order_product_ids));
        if ($result2->num_rows() <= 0) {
            return ;
        }
        $orderPoductProfit = $result2->result();
        $this->db->trans_begin();
        $isProfit = $this->operatingProfit($orderPoductProfit); //产品分润
        $isFreight = $this->distributionFreight($orders); //运费分润
        //对订单下的产品进行好评处理
        $isReviews = $this->tourism_order_reviews->insertBatchReviews($orderReviews);
        $isUpdate = $this->tourism_order->reviewsTourismOrder($order_ids); //订单状态修改

        if ($this->db->trans_status() === FALSE || !$isProfit || !$isFreight || !$isReviews || !$isUpdate) {
            $this->db->trans_rollback();
        } else {
            $this->db->trans_commit();
        }
        echo implode(',', $order_ids);exit;
    }

    /***
     * 分钱操作  1，给账户分钱
     *          2，插入分钱记录
     *          3，插入分润记录
     * @param $orderProductProfit
     * @return bool
     */
    public function operatingProfit($orderProductProfit)
    {
        $accountLogData = array();
        $userAccountData = array();
        foreach ($orderProductProfit as $key => $item) {
            if ($item->uid <= 0 || $item->account <= 0) {
                continue;
            }
            $account_name = getAccountNameByAccountID($item->account_type); //可提现或月结 （字段）

            if ($item->as == 2) { //减
                $total_name = 'outlay_total';  //总支出
                $total_amount = $item->account;
            } else {
                $total_name = 'income_total';  //总收入
                $total_amount = $item->account;
            }
            $this->user_account->updateUserAccountProfit($account_name, $total_name, $total_amount, $item);
            $userAccountData[$item->uid]['uid'] = $item->uid;
            if ($item->account_type == ACCOUNT_TYPE_MONTH) { //到付
                $type = DFPROFIT;
            } else { //在线利润
                $type = ZFPROFIT;
            }
            $accountLogData[$key] = $item;
            $accountLogData[$key]->order_id = $item->order_product_id;
            $accountLogData[$key]->type = $type;
        }
        $accountLog = $this->account_log->insertBatchAccountLog($accountLogData);
        if (!$accountLog) {
            return false;
        }
        return true;
    }

    /**
     * 给供应商 分运费的钱
     * @param $tourismOrder
     */
    public function distributionFreight($orders)
    {
        $accountLog = array();
        foreach ($orders as $key => $order) {
            if (!empty($order->seller_uid) && $order->transport_cost > 0) {
                $freight = $this->user_account->updateUserAccountFreight($order->seller_uid, $order->transport_cost);
                if (!$freight) {
                    return false;
                }
                $accountLog[$key]['order_id']     = $order->order_id;
                $accountLog[$key]['uid']          = $order->seller_uid;
                $accountLog[$key]['amount']       = $order->transport_cost;
                $accountLog[$key]['type']         = TOURISMFREIGHT;
                $accountLog[$key]['account_type'] = ACCOUNT_TYPE_CARRY;
                $accountLog[$key]['product_type'] = 'tourism';
                $accountLog[$key]['date']         = date('Y-m-d H:i:s', time());
            }
        }
        if (!empty($accountLog)) {
            $log = $this->account_log->insertBatch($accountLog);
            if (!$log) {
                return false;
            }
        }
        return true;
    }
}